import React, { useState, useEffect } from 'react';
import styles from './index.module.scss';
import Head from 'next/head';
import { Search, Star, ArrowRight, LogoGithub, DataShare } from '@carbon/icons-react';
import mcpData from './data.json';

const LoadingSpinner = () => (
  <div className={styles.loadingSpinner}>
    <div className={styles.spinner}></div>
  </div>
);

const MCPHub = () => {
  const [searchQuery, setSearchQuery] = useState('');
  const [filters, setFilters] = useState({
    category: 'All',
    requiresConfig: 'All',
    hasGithub: 'All',
  });
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [favorites, setFavorites] = useState([]);
  const [filteredServers, setFilteredServers] = useState([]);
  const [activeServer, setActiveServer] = useState(null);

  useEffect(() => {
    // Load favorites from localStorage
    const savedFavorites = localStorage.getItem('mcpFavorites');
    if (savedFavorites) {
      setFavorites(JSON.parse(savedFavorites));
    }
    
    // Initialize data
    if (mcpData?.data?.records) {
      setFilteredServers(mcpData.data.records);
      setLoading(false);
    } else {
      setError('Failed to load MCP servers data');
      setLoading(false);
    }
  }, []);

  const toggleFavorite = (serverId) => {
    const newFavorites = favorites.includes(serverId)
      ? favorites.filter(id => id !== serverId)
      : [...favorites, serverId];
    
    setFavorites(newFavorites);
    localStorage.setItem('mcpFavorites', JSON.stringify(newFavorites));
  };

  const handleSearch = () => {
    if (!mcpData?.data?.records) return;

    let filtered = mcpData.data.records;

    // Apply search filter
    if (searchQuery) {
      const query = searchQuery.toLowerCase();
      filtered = filtered.filter(server => 
        server.name.toLowerCase().includes(query) ||
        server.description.toLowerCase().includes(query)
      );
    }

    // Apply category filters
    if (filters.requiresConfig !== 'All') {
      filtered = filtered.filter(server => 
        server.requires_configuration === (filters.requiresConfig === 'Yes')
      );
    }

    if (filters.hasGithub !== 'All') {
      filtered = filtered.filter(server => 
        (server.github_html_url !== null) === (filters.hasGithub === 'Yes')
      );
    }

    setFilteredServers(filtered);
  };

  useEffect(() => {
    handleSearch();
  }, [searchQuery, filters]);

  const handleServerClick = (server) => {
    setActiveServer(activeServer?.id === server.id ? null : server);
  };

  if (loading) {
    return (
      <div className={styles.loading}>
        <LoadingSpinner />
        <p>Loading MCP servers...</p>
      </div>
    );
  }

  if (error) {
    return (
      <div className={styles.error}>
        <h2>Error</h2>
        <p>{error}</p>
      </div>
    );
  }

  return (
    <>
      <Head>
        <title>MCP Hub - Model Context Protocol Servers</title>
        <meta name="description" content="Connect your AI assistants to powerful MCP servers" />
      </Head>
      
      <div className={styles.mcpHubContainer}>
        <div className={styles.header}>
          <h1>Model Context Protocol <span>Servers</span></h1>
          <p>Explore the most comprehensive and up-to-date collection of MCP servers worldwide.</p>
        </div>

        <div className={styles.searchBar}>
          <Search size={20} className={styles.searchIcon} />
          <input 
            type="text" 
            placeholder="Search MCP servers..."
            value={searchQuery}
            onChange={(e) => setSearchQuery(e.target.value)}
          />
        </div>

        {/* <div className={styles.filters}>
          <div className={styles.filterGroup}>
            <label>Requires Configuration</label>
            <select 
              value={filters.requiresConfig}
              onChange={(e) => setFilters({...filters, requiresConfig: e.target.value})}
            >
              <option value="All">All</option>
              <option value="Yes">Yes</option>
              <option value="No">No</option>
            </select>
          </div>

          <div className={styles.filterGroup}>
            <label>Has GitHub</label>
            <select 
              value={filters.hasGithub}
              onChange={(e) => setFilters({...filters, hasGithub: e.target.value})}
            >
              <option value="All">All</option>
              <option value="Yes">Yes</option>
              <option value="No">No</option>
            </select>
          </div>
        </div> */}

        <div className={styles.serverList}>
          <div className={styles.listHeader}>
            <h2>Available Servers ({filteredServers.length})</h2>
          </div>
          <div className={styles.serverGrid}>
            {filteredServers.map(server => (
              <div 
                key={server.id} 
                className={`${styles.serverCard} ${activeServer?.id === server.id ? styles.active : ''}`}
                onClick={() => handleServerClick(server)}
              >
                <div className={styles.cardHeader}>
                  <div className={styles.headerText}>
                    <div className={styles.iconPlaceholder}>
                      <DataShare size={20} />
                    </div>
                    <h3>{server.name}</h3>
                  </div>
                  {server.github_html_url && (
                    <div className={styles.githubLink}>
                      <button 
                        className={styles.connect}
                        onClick={(e) => e.stopPropagation()}
                      >
                        <LogoGithub size={18} />
                      </button>
                    </div>
                  )}
                </div>
                <p className={styles.description}>{server.description}</p>
                <div className={styles.tags}>
                  {server.requires_configuration && (
                    <span className={styles.configTag}>Requires Config</span>
                  )}
                  <span className={styles.serverNameTag}>{server.server_name}</span>
                </div>
                {/* <div className={styles.actions}>
                  <button 
                    className={`${styles.favorite} ${favorites.includes(server.id) ? styles.active : ''}`}
                    onClick={(e) => {
                      e.stopPropagation();
                      toggleFavorite(server.id);
                    }}
                  >
                    <Star size={16} />
                  </button>
                  {server.github_html_url && (
                    <a 
                      href={server.github_html_url} 
                      target="_blank" 
                      rel="noopener noreferrer"
                      className={styles.github}
                      onClick={(e) => e.stopPropagation()}
                    >
                      View on GitHub
                    </a>
                  )}
                  <button 
                    className={styles.connect}
                    onClick={(e) => e.stopPropagation()}
                  >
                    Connect <ArrowRight size={16} />
                  </button>
                </div> */}
                {activeServer?.id === server.id && (
                  <div className={styles.serverDetails}>
                    <h4>Server Details</h4>
                    <div className={styles.detailItem}>
                      <span>Command:</span>
                      <code>{server.command}</code>
                    </div>
                    {server.args && (
                      <div className={styles.detailItem}>
                        <span>Arguments:</span>
                        <code>{server.args.join(' ')}</code>
                      </div>
                    )}
                  </div>
                )}
              </div>
            ))}
          </div>
        </div>
      </div>
    </>
  );
};

export default MCPHub;